package com.softer.chengxin.system.service.impl;

import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.common.domin.CommonResult;
import com.softer.chengxin.common.enums.ResultEnum;
import com.softer.chengxin.common.util.MD5;
import com.softer.chengxin.system.dao.SystemManageDao;
import com.softer.chengxin.system.service.SystemManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author Gong Zhiyang
 * @date 2018/10/23
 */
@Service
public class SystemManageServiceImpl implements SystemManageService {
    @Autowired
    private SystemManageDao systemManageDao;

    /**
     * 修改密码
     *
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return 修改结果
     */
    @Override
    public CommonResult updatePwd(String oldPwd, String newPwd, HttpSession session) {
        String loginName = (String) session.getAttribute(Common.LOGIN_NAME);
        String loginType = (String) session.getAttribute(Common.LOGIN_TYPE);
        oldPwd = MD5.EncoderByMd5(oldPwd);
        String pwd = "";
        if (Common.ZERO.equals(loginType)) {
            //管理部门
            pwd = systemManageDao.getManagePwd(loginName);
        } else if (Common.ONE.equals(loginType)) {
            //物业企业
            pwd = systemManageDao.getCorpPwd(loginName);
        }
        if (!pwd.equals(oldPwd)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "原密码错误！");
        }
        newPwd = MD5.EncoderByMd5(newPwd);
        int num = Integer.parseInt(Common.ZERO);
        if (Common.ZERO.equals(loginType)) {
            //管理部门
            num = systemManageDao.updateManagePwd(loginName, newPwd);
        } else if (Common.ONE.equals(loginType)) {
            //物业企业
            num = systemManageDao.updateCorpPwd(loginName, newPwd);
        }
        return response(num);
    }

    /**
     * 重置密码
     *
     * @param qyNo 企业账号
     * @return 修改结果
     */
    @Override
    public CommonResult resetPassword(String qyNo) {
        String pwd = MD5.EncoderByMd5("Aa123456");
        int num = systemManageDao.updateCorpPwd(qyNo, pwd);
        return response(num);
    }

    /**
     * 返回结果
     *
     * @param num 处理结果数量
     * @return 返回结构
     */
    private CommonResult response(int num) {
        if (num > Integer.parseInt(Common.ZERO)) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }
}
